package com.hqu.controller;

import com.hqu.dao.CourseRepository;
import com.hqu.dao.StudentRepository;
import com.hqu.mapper.CourseMapper;
import com.hqu.entity.Course;
import com.hqu.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private CourseMapper courseMapper;
    @GetMapping("/setStudentInfo")
    public String setStudentInfo(Model model){
        model.addAttribute("student",new Student());
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //主体名，即登录用户名
        model.addAttribute("username",name);
        return "studentInfo";
    }

    @PostMapping("/checkCourse")
    public String checkCourse(@Valid @ModelAttribute("student") Student student, Errors error, Model model){
        if (error.hasErrors()){
            return "studentInfo";
        }

        List<Course> courses = courseMapper.queryAllCourses();
        model.addAttribute("allCourses",courses);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //主体名，即登录用户名
        model.addAttribute("username",name);
        return "checkCourse";

    }

    @PostMapping("/displayStudent")//展示所选学生信息与课程信息
    public String displayStudent(Student student, Model model, HttpServletRequest request){
        System.out.println(student);
        //拿到所选课程的id
        String[] courseChecks = request.getParameterValues("courseCheck");

        for (String courseCheck : courseChecks) {
            //根据id查询所选课程
            Course course = courseMapper.queryCourseById(Integer.parseInt(courseCheck));
            System.out.println(course);
            student.getCourses().add(course);
        }
        System.out.println(student);
        studentRepository.save(student);
        model.addAttribute("student",student);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //主体名，即登录用户名
        model.addAttribute("username",name);
        return "displayStudent";
    }

}
